<!-- create.vue -->
<template>
  <view class="task-detail">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left" @click="goBack">
        <uni-icons type="left" size="20"></uni-icons>
        <text>返回</text>
      </view>
      <view class="title">创建任务</view>
      <view class="right" @click="createTask">
        <text>创建</text>
      </view>
    </view>

    <!-- 任务内容 -->
    <view class="content">
      <!-- 基本信息 -->
      <view class="section">
        <view class="section-title">基本信息</view>
        <view class="form-item">
          <text class="label">标题</text>
          <input 
            type="text" 
            v-model="task.title"
            class="input" 
            placeholder="请输入任务标题"
          />
        </view>
        <view class="form-item">
          <text class="label">负责人</text>
          <picker 
            mode="selector" 
            :range="assignees" 
            range-key="name"
            @change="onAssigneeChange"
          >
            <view class="picker">
              {{ assignees.find(a => a.id === task.assignee)?.name || '请选择负责人' }}
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">优先级</text>
          <picker 
            mode="selector" 
            :range="priorities" 
            range-key="name"
            @change="onPriorityChange"
          >
            <view class="picker">{{ task.priority.name || '请选择优先级' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">状态</text>
          <picker 
            mode="selector" 
            :range="statuses" 
            range-key="name"
            @change="onStatusChange"
          >
            <view class="picker">{{ task.status.name || '请选择状态' }}</view>
          </picker>
        </view>
      </view>

      <!-- 任务描述 -->
      <view class="section">
        <view class="section-title">任务描述</view>
        <textarea 
          v-model="task.description"
          class="description-input"
          placeholder="请输入任务描述"
        />
        <!-- 文件上传区域 -->
        <view class="upload-section">
          <view class="upload-title">附件</view>
          <!-- 已上传文件列表 -->
          <view class="file-list" v-if="uploadedFiles.length > 0">
            <view class="file-item" v-for="(file, index) in uploadedFiles" :key="index">
              <view class="file-info">
                <uni-icons type="file" size="20" color="#666"></uni-icons>
                <text class="file-name">{{ file.name }}</text>
              </view>
              <view class="file-actions">
                <text class="delete-btn" @click="deleteFile(index)">删除</text>
              </view>
            </view>
          </view>
          <!-- 上传按钮 -->
          <button class="upload-btn" @click="chooseFile">
            <uni-icons type="upload" size="20"></uni-icons>
            <text>上传文件</text>
          </button>
        </view>
      </view>

      <!-- 时间信息 -->
      <view class="section">
        <view class="section-title">时间信息</view>
        <view class="form-item">
          <text class="label">开始时间</text>
          <picker 
            mode="date" 
            :value="task.startTime || ''"
            @change="onStartTimeChange"
          >
            <view class="picker">{{ task.startTime || '请选择开始时间' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">结束时间</text>
          <picker 
            mode="date" 
            :value="task.endTime || ''"
            @change="onEndTimeChange"
          >
            <view class="picker">{{ task.endTime || '请选择结束时间' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">进度</text>
          <slider 
            :value="task.progress"
            @change="onProgressChange"
            show-value
            min="0"
            max="100"
            step="5"
          />
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import type { Task, Assignee, Priority, Status } from '../../types/task'
import { taskApi } from '../../services/task'

// 初始化一个空的任务对象
const task = ref<Task>({
  id: '',
  title: '',
  description: '',
  assignee: '',
  priority: {
    id: '',
    name: '',
    color: ''
  },
  status: {
    id: '',
    name: '',
    color: ''
  },
  startTime: '',
  endTime: '',
  progress: 0
})

const assignees = ref<Assignee[]>([])
const priorities = ref<Priority[]>([])
const statuses = ref<Status[]>([])

// 获取选项数据
const fetchOptions = async () => {
  try {
    const options = await taskApi.getOptions()
    assignees.value = options.assignees
    priorities.value = options.priorities
    statuses.value = options.statuses
  } catch (err) {
    uni.showToast({
      title: '获取选项数据失败',
      icon: 'error'
    })
  }
}

// 事件处理函数
const onAssigneeChange = (e: { detail: { value: number } }) => {
  const selectedAssignee = assignees.value[e.detail.value]
  if (selectedAssignee) {
    task.value.assignee = selectedAssignee.id
  }
}

const onPriorityChange = (e: { detail: { value: number } }) => {
  const selectedPriority = priorities.value[e.detail.value]
  if (selectedPriority) {
    task.value.priority = {
      id: selectedPriority.id,
      name: selectedPriority.name,
      color: selectedPriority.color
    }
  }
}

const onStatusChange = (e: { detail: { value: number } }) => {
  const selectedStatus = statuses.value[e.detail.value]
  if (selectedStatus) {
    task.value.status = {
      id: selectedStatus.id,
      name: selectedStatus.name,
      color: selectedStatus.color
    }
  }
}

const onStartTimeChange = (e: { detail: { value: string } }) => {
  task.value.startTime = e.detail.value
}

const onEndTimeChange = (e: { detail: { value: string } }) => {
  task.value.endTime = e.detail.value
}

const onProgressChange = (e: { detail: { value: number } }) => {
  task.value.progress = e.detail.value
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 文件上传相关
interface UploadedFile {
  name: string;
  url: string;
  size: number;
}

const uploadedFiles = ref<UploadedFile[]>([])

// 选择文件
const chooseFile = () => {
  // @ts-ignore
  uni.chooseFile({
    count: 1,
    extension: ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt', '.png', '.jpg', '.jpeg'],
    success: (res: any) => {
      const tempFiles = Array.isArray(res.tempFiles) ? res.tempFiles : [res.tempFiles]
      if (tempFiles.length > 0) {
        const file = tempFiles[0]
        const uploadedFile = {
          name: file.name || `文件_${Date.now()}`,
          path: file.path,
          size: file.size || 0
        }
        uploadFile(uploadedFile)
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '选择文件失败',
        icon: 'none'
      })
    }
  })
}

// 上传文件
const uploadFile = async (file: { name: string; path: string; size: number }) => {
  try {
    const uploadedFile: UploadedFile = {
      name: file.name,
      url: file.path,
      size: file.size
    }
    uploadedFiles.value.push(uploadedFile)
    uni.showToast({
      title: '上传成功',
      icon: 'success'
    })
  } catch (err) {
    uni.showToast({
      title: '上传失败',
      icon: 'none'
    })
  }
}

// 删除文件
const deleteFile = (index: number) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除该文件吗？',
    success: (res) => {
      if (res.confirm) {
        uploadedFiles.value.splice(index, 1)
      }
    }
  })
}

// 修改创建任务函数，包含文件信息
const createTask = async () => {
  // 表单验证
  if (!task.value.title) {
    uni.showToast({
      title: '请输入任务标题',
      icon: 'none'
    })
    return
  }
  if (!task.value.assignee) {
    uni.showToast({
      title: '请选择负责人',
      icon: 'none'
    })
    return
  }
  if (!task.value.priority.id) {
    uni.showToast({
      title: '请选择优先级',
      icon: 'none'
    })
    return
  }
  if (!task.value.status.id) {
    uni.showToast({
      title: '请选择状态',
      icon: 'none'
    })
    return
  }

  try {
    // 创建包含文件信息的任务数据
    const taskData = {
      ...task.value,
      attachments: uploadedFiles.value
    }
    await taskApi.createTask(taskData)
    uni.showToast({
      title: '创建成功',
      icon: 'success'
    })
    setTimeout(() => {
      goBack()
    }, 1500)
  } catch (err) {
    uni.showToast({
      title: '创建失败',
      icon: 'error'
    })
  }
}

// 页面加载时获取选项数据
onMounted(() => {
  fetchOptions()
})
</script>

<style lang="scss">
.task-detail {
  min-height: 100vh;
  background: #f5f7fa;
  
  .nav-bar {
    background: #4a6ee0;
    padding: 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;
    
    .left {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      
      .uni-icons {
        margin-right: 8rpx;
      }
    }
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .right {
      font-size: 28rpx;
      padding: 8rpx 24rpx;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 32rpx;
      
      &:active {
        opacity: 0.8;
      }
    }
  }
  
  .content {
    padding: 24rpx;
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    
    .section {
      background: #fff;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 24rpx;
      
      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 16rpx;
      }
      
      .form-item {
        margin-bottom: 24rpx;
        
        .label {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 8rpx;
          display: block;
        }
        
        .input {
          border: 2rpx solid #eee;
          border-radius: 8rpx;
          padding: 16rpx;
          font-size: 28rpx;
        }
        
        .picker {
          border: 2rpx solid #eee;
          border-radius: 8rpx;
          padding: 16rpx;
          font-size: 28rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }
    
    .description-input {
      border: 2rpx solid #eee;
      border-radius: 8rpx;
      padding: 16rpx;
      font-size: 28rpx;
      width: 100%;
      height: 200rpx;
    }
  }
}

.upload-section {
  margin-top: 24rpx;
  
  .upload-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
  }
  
  .file-list {
    margin-bottom: 16rpx;
    
    .file-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16rpx;
      background: #f8f9fa;
      border-radius: 8rpx;
      margin-bottom: 12rpx;
      
      .file-info {
        display: flex;
        align-items: center;
        flex: 1;
        
        .uni-icons {
          margin-right: 8rpx;
        }
        
        .file-name {
          font-size: 28rpx;
          color: #333;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      
      .file-actions {
        .delete-btn {
          font-size: 24rpx;
          color: #f56c6c;
          padding: 4rpx 12rpx;
          
          &:active {
            opacity: 0.8;
          }
        }
      }
    }
  }
  
  .upload-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16rpx;
    background: #f8f9fa;
    border: 2rpx dashed #ddd;
    border-radius: 8rpx;
    
    .uni-icons {
      margin-right: 8rpx;
    }
    
    text {
      font-size: 28rpx;
      color: #666;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}
</style> 